﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using ElingOA6_Admin_DSJCJ.Models;
using System.Data;
using DevExpress.Web.Mvc;
using Newtonsoft.Json;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 问卷题目管理
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class PaperTopicController : AdminBaseController
    {
        //
        // GET: /Admin/PaperTopic/
        /// <summary>
        /// 问卷题目管理主页
        /// </summary>
        /// <returns>主页视图</returns>
        [AuthorityActionFilter("m_PaperTopic", Order = 1)]
        [LogPageActionFilter("问卷题目管理", Order = 2)]
        public ActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// 树
        /// </summary>
        /// <returns>树视图</returns>
        public ActionResult PaperTopicTree()
        {
            TreeModelList treeModelList = new TreeModelList();
            BLL.PaperCls paperClsBll = new BLL.PaperCls();
            List<Model.PaperCls> paperClsList = paperClsBll.GetModelList(GlobalConstant.ENTITYNO);

            BLL.Paper paperBll = new BLL.Paper();
            List<Model.Paper> paperList = paperBll.GetModelList("FEntityNo='" + GlobalConstant.ENTITYNO + "'");

            if (paperClsList.Count > 0)
            {
                foreach (Model.PaperCls paperCls in paperClsList)
                {
                    TreeItemModel treeParentItemModel = new TreeItemModel(null)
                    {
                        Id = paperCls.FPaperClsNo,
                        Name = paperCls.FPaperClsName,
                        ImageUrl = Url.Content("~/Content/ControlImages/scripts_code.png")

                    };

                    var query = paperList.Where(c => c.FPaperClsNo == paperCls.FPaperClsNo);

                    if (paperList.Count > 0)
                    {
                        foreach (Model.Paper paper in query)
                        {
                            TreeItemModel treeSonItemModel = new TreeItemModel(treeParentItemModel)
                            {
                                Id = paper.FPaperId.ToString(),
                                Name = paper.FTitle,
                                ImageUrl = Url.Content("~/Content/ControlImages/scripts_code.png")

                            };

                        }
                    }

                    treeModelList.Add(treeParentItemModel);
                }


            }

            return View(treeModelList);

        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="paperId">类别编号</param>
        /// <returns>列表视图</returns>
        public ActionResult PaperTopicList(string paperId)
        {
            ViewData["add"] = false;
            int pageIndex = 1;
            List<Model.PaperTopic> paperTopicList = GetPaperTopicList(paperId, pageIndex);

            //判断是否已存在答题
            decimal decPaperID = 0;
            decimal.TryParse(paperId, out decPaperID);
            BLL.PaperAnswerManager paperAnswerManagerBll = new BLL.PaperAnswerManager();
            string isAnswer = "";
            if (paperAnswerManagerBll.ExistsByPaperId(decPaperID))
            {
                isAnswer = "Y";
            }
            else
            {
                isAnswer = "N";
            }

            if (null == paperId || isAnswer == "Y")
            {
                ViewData["add"] = false;
            }
            else {
                ViewData["add"] = true;
            }
            
            ViewData["paperID"] = paperId;
            ViewData["isAnswer"] = isAnswer;
            return View(paperTopicList);

        }


        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="paperId">类别编号</param>
        /// <param name="pageIndex">第几页</param>
        /// <param name="pageRowSize">页吗大小</param>
        /// <returns>数据集合</returns>
        private List<Model.PaperTopic> GetPaperTopicList(string paperId, int pageIndex, int pageRowSize = 0)
        {
            if (null != paperId)
            {
                paperId = Fetch.estimateString(paperId, CheckGetEnum.Safety);
            }
            else
            {
                paperId = string.Empty;
            }


            BLL.PaperTopic paperTopicBll = new BLL.PaperTopic();

            string where = "FEntityNo='" + GlobalConstant.ENTITYNO + "'";

            if (paperId != "")
            {
                where += "and FPaperId='" + paperId + "'";
            }

            BLL.Common commonBll = new BLL.Common();
            string fiedls = "*";
            int total;

            DataSet ds = commonBll.GetListByPage("v_PaperTopic_Paper", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex, where, "FPaperTopicId", 0, out total);


            List<Model.PaperTopic> paperTopicAllList = new List<Model.PaperTopic>();
            List<Model.PaperTopic> paperTopicList = paperTopicBll.DataTableToListPaperTopic(ds.Tables[0]);

            pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            for (int i = 0; i < total; i++)
            {
                paperTopicAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (paperTopicList.Count > i)
                {
                    paperTopicAllList[((pageIndex - 1) * pageRowSize) + i] = paperTopicList[i];
                }
            }
            return paperTopicAllList;
        }



        /// <summary>
        /// 用于刷新
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult PaperTopciListPartial()
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string paperId = Request.Params["paperTopicId"];
            string callbackArg = DevExpressHelper.CallbackArgument;
            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }


            List<Model.PaperTopic> paperTopicList = GetPaperTopicList(paperId, pageIndex, pageRowSize);


            return PartialView("PaperTopciListPartial", paperTopicList);

        }

        /// <summary>
        /// 增加修改
        /// </summary>
        /// <param name="paperId">类别编号</param>
        /// <param name="paperTopicId">题目编号</param>
        /// <returns>增加修改视图</returns>

        public ActionResult PaperTopicContent(string paperId, string paperTopicId)
        {
            Model.PaperTopic paperTopicModel = new Model.PaperTopic();
            ViewData["title"] = "";
            ViewData["topic"] = "";
            ViewData["shortAnswerCount"] = "";
            if (null != paperTopicId) { //修改
                ViewData["hdMethod"] = "Edit";
                BLL.PaperTopic paperTopicBll = new BLL.PaperTopic();
                Model.PaperTopic paperTopicObj = paperTopicBll.GetModel(decimal.Parse(paperTopicId));
                if (null != paperTopicObj)
                {
                    SetBzdz(paperTopicObj.FPaperId);
                    if (paperTopicObj.FTopicType == "A")
                    {
                        ViewData["hidIsAnswer"] = "0";
                        ViewData["hidJdt"] = "1";
                    }

                    ViewData["hidPaperID"] = paperTopicObj.FPaperId.ToString();
                    ViewData["hidPaperTopicID"] = paperTopicObj.FPaperTopicId.ToString();


                    //判断是否已存在该题目的答题
                    BLL.PaperAnswer answerBll = new BLL.PaperAnswer();
                    if (answerBll.ExistsByTopicID(decimal.Parse(paperTopicId)))
                    {
                        ViewData["hidIsAnswer"] = "1";
                    }


                    //绑定已有的答案选择项
                    BLL.PaperAnswerOption paperAnswerOptionBll = new BLL.PaperAnswerOption();

                    List<Model.PaperAnswerOption> paperAnswerOptionList = paperAnswerOptionBll.GetModelList(" FPaperTopicId=" + paperTopicId + " order by FAnswerNo");
                    ViewData["hidEditCount"] = paperAnswerOptionList.Count;
                    string _jsonstr = "";
                    _jsonstr += JsonConvert.SerializeObject(paperAnswerOptionList);

                    ViewData["PaperTopicList"] = _jsonstr;


                    //绑定页面
                    ViewData["topic"] = paperTopicObj.FTopic;
                    ViewData["shortAnswerCount"] = paperTopicObj.FShortAnswerCount.HasValue ? paperTopicObj.FShortAnswerCount.Value.ToString() : "0";
                    paperTopicModel.FStdAnswer = paperTopicObj.FStdAnswer;
                    paperTopicModel.FTopicType = paperTopicObj.FTopicType;

                }
            }
            else if(null != paperId){//增加
                SetBzdz(decimal.Parse(paperId));
                ViewData["hidEditCount"] = "0";
                ViewData["hidPaperID"] = paperId.ToString();
                ViewData["hidPaperTopicID"] = "0";
                ViewData["topic"] = "";
                ViewData["shortAnswerCount"] = "";
                paperTopicModel.FTopicType = "R";
            }
            return View(paperTopicModel);
        }


        /// <summary>
        /// 普通的方法
        /// </summary>
        /// <param name="paperID">题目编号</param>
        private void SetBzdz(decimal paperID)
        {
            BLL.Paper paperBll = new BLL.Paper();
            Model.Paper paperObj = paperBll.GetModel(paperID);
            if (null != paperObj)
            {
                if (paperObj.FPaperType == "T")
                {
                    ViewData["hidbzdz"] = "1";
                }
                ViewData["title"] = paperObj.FTitle;
            }
        }


        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="topic">题目的信息</param>
        /// <param name="answerOption">答案的信息</param>
        /// <returns>返回是否成功保存</returns>
        public string PaperTopicAdd(string topic, string answerOption)
        {
            ViewData["title"] = "";
            ViewData["topic"] = "";
            ViewData["shortAnswerCount"] = "";
            Model.PaperTopic paperTopicObj = new Model.PaperTopic();

            List<Model.PaperAnswerOption> paperAnswerTopicList = new List<Model.PaperAnswerOption>();
            if (topic != string.Empty)
            {
                paperTopicObj = Newtonsoft.Json.JsonConvert.DeserializeObject<Model.PaperTopic>(topic);
                paperTopicObj.FPubDate = DateTime.Now;
                paperTopicObj.FPubDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                paperTopicObj.FPubEmpNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                paperTopicObj.FPubIp = Common.GenerateUtil.GetClientIPv4Address();
            }
            if (answerOption != string.Empty)
            {
                paperAnswerTopicList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Model.PaperAnswerOption>>(answerOption);
            }

            string str = string.Empty;
            BLL.PaperTopic paperTopicBll = new BLL.PaperTopic();
            try
            {
                paperTopicBll.AddTopicAndAnswerOption(paperTopicObj, paperAnswerTopicList);
                str = "ok";
                ViewData["message"] = "操作成功";
                ViewData["IsClose"] = "Y";
            }
            catch (Exception)
            {
                str = "error";
                ViewData["message"] = "保存失败";
                ViewData["IsClose"] = "N";
            }

            return str + "," + paperTopicObj;
        
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="topic">题目的信息</param>
        /// <param name="answerOption">答案的信息</param>
        /// <returns>返回是否成功修改</returns>
        public string PaperTopicEdit(string topic, string answerOption)
        {
            string str = string.Empty;
            Model.PaperTopic paperTopicObj = new Model.PaperTopic();
            List<Model.PaperAnswerOption> paperAnswerTopicList = new List<Model.PaperAnswerOption>();
            if (topic != string.Empty)
            {
                paperTopicObj = Newtonsoft.Json.JsonConvert.DeserializeObject<Model.PaperTopic>(topic);
                paperTopicObj.FPubDate = DateTime.Now;
                paperTopicObj.FPubDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                paperTopicObj.FPubEmpNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                paperTopicObj.FPubIp = Common.GenerateUtil.GetClientIPv4Address();
            }
            if (answerOption != string.Empty)
            {
                paperAnswerTopicList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Model.PaperAnswerOption>>(answerOption);
            }

            BLL.PaperTopic topicBll = new BLL.PaperTopic();
            try
            {
                topicBll.UpdTopicAndAnswerOption(paperTopicObj, paperAnswerTopicList);
                str = "ok";
            }
            catch (Exception)
            {
                str = "error";
            }

            return str;
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="topicIds">题目编号</param>
        /// <returns>是否成功删除</returns>
        public string DelTopicAndAnswerOptionMany(string topicIds)
        {
            string str = string.Empty;
            if (topicIds != string.Empty)
            {
                topicIds = topicIds.TrimEnd(',');
                List<decimal> paperTopicIdList = new List<decimal>();
                foreach (string topicId in topicIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                {
                    paperTopicIdList.Add(decimal.Parse(topicId));
                }

                BLL.PaperAnswer paperAnswerBll = new BLL.PaperAnswer();
                List<decimal> existsAnswerList = paperAnswerBll.GetAnswerExistsByTopicIDS(topicIds);

                paperTopicIdList = paperTopicIdList.Except(existsAnswerList).ToList();

                BLL.PaperTopic topicBll = new BLL.PaperTopic();
                try
                {
                    topicBll.DelTopicAndAnswerOptionMany(paperTopicIdList);

                    if (existsAnswerList.Count > 0)
                    {
                        string notDel = ",";
                        existsAnswerList.ForEach(c => notDel += c + ",");
                        str = "okExists_" + notDel;
                    }
                    else
                    {
                        str = "ok";
                    }
                }
                catch (Exception)
                {

                    str = "error";
                }
            }
            return str;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="paperTopicId">题目编号</param>
        /// <returns>是否删除成功</returns>
        public string DelTopicAndAnswerOption(string paperTopicId)
        {
            string str = string.Empty;
            BLL.PaperAnswer answerBll = new BLL.PaperAnswer();
            BLL.PaperTopic paperTopicBll = new BLL.PaperTopic();
            try
            {
                if (answerBll.ExistsByTopicID(decimal.Parse(paperTopicId)))
                {
                    str = "Exists";
                }
                else {
                    paperTopicBll.DelTopicAndAnswerOption(decimal.Parse(paperTopicId));
                    str = "ok";
                }                    
               
            }
            catch (Exception)
            {
                str = "error";
            }
            return str;
        }

        /// <summary>
        /// 答案选项的集合
        /// </summary>
        private readonly List<string> answerNoList = new List<string> { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P" };
        /// <summary>
        /// 答案选择项删除
        /// </summary>
        /// <param name="topicID">题目编号</param>
        /// <param name="answerNo">问题答案</param>
        /// <param name="nextAnswerNos">问题剩下的答案</param>
        /// <returns>答案选择项删除是否成功</returns>
        public string DelAnswerOption(decimal topicID, string answerNo, string nextAnswerNos)
        {
            string str = string.Empty;
            if (topicID != 0 && answerNo != string.Empty)
            {
                BLL.PaperAnswerOption paperAnswerOptonBll = new BLL.PaperAnswerOption();
                List<Model.PaperAnswerOption> updAnswerOptionList = new List<Model.PaperAnswerOption>();
                if (nextAnswerNos.Length > 0)
                {
                    Model.PaperAnswerOption model;
                    string[] nextAnswerNoArray = nextAnswerNos.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string no in nextAnswerNoArray)
                    {
                        model = new Model.PaperAnswerOption();
                        model.FPaperTopicId = topicID;
                        model.FAnswerNo = no;
                        model.FAnswerContent = answerNoList[answerNoList.IndexOf(no) - 1];
                        updAnswerOptionList.Add(model);
                    }

                }
                try
                {
                    paperAnswerOptonBll.DelAndUpdAnswerNo(topicID, answerNo, updAnswerOptionList);
                    str = "ok";
                }
                catch (Exception)
                {
                    str = "error";
                }


            }
            return str;
        }

    }
}
